<template>
 <div class="addcustomer_container">
  <div class="nav">
    <Breadcrumb separator=">">
        <Breadcrumb-item href="/customer">客户列表</Breadcrumb-item>
        <!-- num -->
        <Breadcrumb-item href="/customer/addcustomer" v-if="memberId>0">编辑客户</Breadcrumb-item>
        <Breadcrumb-item href="/customer/addcustomer" v-else>新建客户</Breadcrumb-item>
    </Breadcrumb>
  </div>
  <div class="clear:both;"></div>
  <div class="basic_attribute">
    <Form ref="formValidate" :model="formValidate" :rules="ruleValidate" :label-width="50" label-position="left">
      <Card>
        <h4 class="basic_tilte">基础属性</h4>
        <Row style="margin-top:2vh;">
          <Col span="6" push="1">
            <FormItem label="会员ID">
              <Input v-model="formValidate.memberId" placeholder="请输入会员ID" style="width:150px;" clearable disabled></Input>
            </FormItem>
          </Col>
          <Col span="6">
            <FormItem label="客户号" :label-width="85">
              <Input v-model="formValidate.number" placeholder="请输入客户号" style="width:150px;" clearable disabled></Input>
            </FormItem>
          </Col>
          <Col span="5">
            <FormItem label="姓名" prop="name">
              <Input v-model="formValidate.name" placeholder="请输入姓名" style="width:150px;" clearable></Input>
            </FormItem>
          </Col>
          <Col span="6">
            <FormItem label="性别" :label-width="85">
              <Select v-model="formValidate.sex"  style="width:150px;" clearable >
                  <Option value="1">男</Option>
                  <Option value="2">女</Option>
              </Select>
            </FormItem>
          </Col>
        </Row>
        <Row style="margin-top:2vh;">
          <Col span="6" push="1">
            <FormItem label="生日">
              <Row>
                <Col span="11">
                  <DatePicker type="datetime" placeholder="请选择..." v-model="formValidate.birthdayStr" style="width:150px;" format="yyyy-MM-dd"  @on-change="formValidate.birthdayStr=$event"></DatePicker>
                </Col>
              </Row>
            </FormItem>
          </Col>
          <Col span="6">
            <FormItem label="会员手机号" prop="mobile" :label-width="85">
              <Input v-model="formValidate.mobile" placeholder="请输入会员手机号" style="width:150px;" clearable></Input>
            </FormItem>
          </Col>
          <Col span="5">
            <FormItem label="邮件" prop="email">
              <Input v-model="formValidate.email" placeholder="请输入邮件地址" style="width:150px;" clearable></Input>
            </FormItem>
          </Col>
          <Col span="6">
            <FormItem label="会员等级" :label-width="85">
              <Select v-model="formValidate.levelId"  style="width:150px;" @on-open-change="$store.dispatch('fetchlevelRuleList')" clearable >
                  <Option v-for="(item,index) in levelRulelist" :key="index" :value="item.levelId">{{item.levelName}}</Option>
              </Select>
            </FormItem>
          </Col>
        </Row>
        <Row style="margin-top:2vh;">
          <Col span="5" push="1">
            <FormItem label="积分" prop="availablePoints">
              <Input v-model="formValidate.availablePoints" placeholder="请输入积分" style="width:150px;" clearable></Input>
            </FormItem>
          </Col>
          <Col span="18" push="1">
            <FormItem label="常用联系地址" :label-width="85"> 
              <Col >
                  <Row>
                    <Col span="4">
                      <Select v-model="formValidate.province" style="width:150px" clearable @on-change="$store.dispatch('fetchcityList',formValidate.province)">
                          <Option v-for="(item,index) in provincelist" :key="index" :value="item.areaId">{{item.name}}</Option>
                      </Select>
                     </Col>
                    <Col span="4" style="margin-left:1vw;">
                      <Select v-model="formValidate.city" style="width:150px" clearable @on-change="$store.dispatch('fetchdistrictList',formValidate.city)">
                          <Option v-for="(item,index) in citylist" :key="index" :value="item.areaId" >{{item.name}}</Option>
                      </Select>
                    </Col>
                    <Col span="4" style="margin-left:1vw;">
                      <Select v-model="formValidate.district" style="width:150px" clearable >
                        <Option v-for="(item,index) in districtlist" :key="index" :value="item.areaId" >{{item.name}}</Option>
                      </Select>
                    </Col>
                    <Col span="6" style="margin-left:1vw;">
                      <Input v-model="formValidate.address" placeholder="请输入详细地址"  style="width:250px;" clearable/>
                    </Col>
                  </Row>
              </Col>
            </FormItem>
          </Col>
        </Row>
      </Card>
      <!-- 收货人信息 -->
      <Card style="margin-top:2vh">
        <FormItem  
          v-for="(item, index) in formValidate.memberAddressList"
          v-if="item.status"
          :key="index">
          <Row>
              <Col span="21" style="margin-left:-4vw;">
                  <h3 class="consignee_info_title">收货人信息{{index+1}}</h3>
                  <div class="cumulative_consumption_box">
                      <Row style="margin-top:2vh;margin-left:4vw;">
                          <Col span="5">
                              <Label>姓名</Label>
                              <Input v-model="item.name" placeholder="请输入收货人姓名"  style="width:150px;padding-left:1vw;" clearable/>
                          </Col>
                          <Col span="6">
                              <Label>手机号码</Label>
                              <Input v-model="item.mobile" placeholder="请输入收货人手机号"  style="width:140px;padding-left:1vw;" clearable/>
                          </Col>
                          <Col span="12">
                            <Row>
                                <Col span="3">
                                    <Label>收货人地址</Label>
                                </CoL>
                                <Col span="14">
                                  <Row>
                                    <Col span="4" push="1">
                                      <i-select v-model="item.province" style="width:120px" clearable @on-change="getCityListByProvinceId(item.province, index)">
                                        <Option v-for="(item,index) in provincelist" :key="index" :value="item.areaId">{{item.name}}</Option>
                                      </i-select>
                                    </Col>
                                    <Col span="4" push="8">
                                      <i-select v-model="item.city" style="width:120px" clearable @on-change="getDistrictListByCityId(item.city, index)">
                                        <Option v-for="(item,indexx) in itemcityList[index]" :key="indexx" :value="item.areaId" >{{item.name}}</Option>
                                      </i-select>
                                    </Col>
                                    <Col span="4" push="15">
                                      <i-select v-model="item.district" style="width:120px" clearable>
                                        <Option v-for="(item,indexx) in itemdistrictList[index]" :key="indexx" :value="item.areaId" >{{item.name}}</Option>
                                      </i-select>
                                    </Col>
                                    <Col span="5" push="22">
                                      <Input v-model="item.address" placeholder="请输入详细地址"  style="width:150px;" clearable/>
                                    </Col>
                                  </Row>
                                </Col>
                            </Row>
                          </Col>
                      </Row>
                  </div>
              </Col>
              <Col span="2" style="margin-left:-1vw;">
                  <Button v-if="item.status==1" @click="handleAdd"><Icon type="ios-add"></Icon>添加收货人</Button>
                  <Button @click="handleRemove(index)" v-else>删除该收货人</Button>
              </Col>
          </Row>
      </FormItem>
      </Card>
      <Row type="flex" justify="center" style="margin-top:2vh;">
        <Col span="2">
          <Button type="primary" @click="submitCustomer('formValidate')" :disabled="disabled">保存</Button>
        </Col>
        <Col span="2">
          <Button type="error" @click="routerback">返回</Button>
        </Col>
      </Row>
    </Form>
  </div>
</div>
</template>
<script>
import { mapState, mapMutations, mapActions } from "vuex";
import { addCustomer, getDetailByid } from '@/api/customer'
import { fetchgradeList} from '@/api/grade';
import { getCityListByProvinceId, getDistrictListByCityId} from '@/api/basic';
export default {
  name: "AddCustomer",
  data() {
    const validateNumber = (rule, value, callback) => {
        if (value % 1 != 0) {
          callback(new Error("请输入整数"));
        } else {
          callback();
        }
    };
    const validateMobile = (rule, value, callback) => {
      var myreg=/^[1][3,4,5,7,8][0-9]{9}$/;
      if (!myreg.test(value)) {
        callback(new Error("请输入手机号"));
      } else {
        callback();
      }
    };

    return {
      levelRulelist: [],
      disabled: false,
      editnum:this.$route.params.num,
      memberId:this.$route.params.id,
      formValidate: {
        memberId: "",
        number: "",
        name: "",
        sex: "",
        levelId: "",
        birthdayStr: "",
        mobile: "",
        email: "",
        province: "",
        city: "",
        address: "",
        availablePoints: "",
        memberAddressList:[
          {
            value: '',
            index: '',
            status: 1,
            name:'',
            mobile:'',
            province:'',
            city:'',
            district:'',
            address:'',
          }
        ]
      },
      itemcityList: [],
      itemdistrictList: [],
      ruleValidate: {
        number: [{ required: true, message: "客户号不能为空", trigger: "blur",validator: validateNumber }],
        name: [{ required: true, message: "请输入姓名", trigger: "blur" }],
        sex: [{ required: true, message: "请选择性别", trigger: "change" }],
        birthday: [{ required: true, message: "请选择时间", trigger: "change" }],
        mobile: [
          { required: true, message: "会员手机号不能为空", trigger: "blur"},
          { validator: validateMobile, message:"请输入手机号", trigger: 'change'}
        ],
        email: [
          { type: "email", message: "邮件地址格式不正确", trigger: "blur" }
        ],
        availablePoints: [
          { validator: validateNumber , message: "请输入数字",trigger: "blur"}
        ],
      },
    };
  },
  components: {},
  methods: {
    ...mapMutations(["FETCH_PROVINCE", "FETCH_CITY", "FETCH_DISTRICT"]),
    ...mapActions(["fetchprovinceLists", "fetchcityList", "fetchdistrictList"]),
    handleAdd () {
      this.index++;
      this.formValidate.memberAddressList.push({
          value: '',
          index: this.index,
          status: 2,
          name:'',
          mobile:'',
          province:'',
          city:'',
          address:'',
      });
      this.itemcityList.push({

      });
      this.itemdistrictList.push({

      });
    },
    handleRemove (index) {
        this.formValidate.memberAddressList[index].status = 0;
    },
    fetchprovincelist(){
      this.$store.dispatch('fetchprovinceLists');
    },
    submitCustomer(name) {       // 保存客户信息
      this.$refs[name].validate((valid) => {
        if (valid) {
          this.disabled = true;
          var reqParams = this.formValidate;
          reqParams.id = this.memberId;
          addCustomer(reqParams).then(res=>{
            if (res.data.code == 200) {
              this.$Message.success("新建客户成功！");
              this.$router.push({path:'/customer/customerList'})
            }
          }).catch(error=>{
            this.$Message.error("操作失败【" + error + "】");
          })
          this.disabled = false;
        } 
      })
    },
    getDetailByid() {
      if (this.memberId){
        getDetailByid(this.memberId).then(res=>{
          if (res.data.code == 200) {
            var i = 0;
            if (res.data.data.memberAddressList && res.data.data.memberAddressList.length > 0){
              res.data.data.memberAddressList.forEach(item =>{
                this.index++;
                if (i == 0){
                  item.status = 1;
                }else{
                  item.status = 2;
                }

                if (item.province){
                  this.getCityListByProvinceId(item.province, i);
                }
                if (item.city){
                  this.getDistrictListByCityId(item.city, i);
                }
                i++;
              });
            }

            this.formValidate = res.data.data;
            if(res.data.data.sex){
              this.formValidate.sex = res.data.data.sex.toString();
            }
            if (this.formValidate.province){
              this.$store.dispatch('fetchcityList', this.formValidate.province);
            }
            if (this.formValidate.city){
              this.$store.dispatch('fetchdistrictList', this.formValidate.city);
            }
          }
        }).catch(error=>{
          this.$Message.error("操作失败【" + error + "】");
        })
      }

    },

    fetchlevelRuleList(){                // 请求公共会员等级列表
      fetchgradeList().then(res=>{
        if (res.data.code == 200) {
          this.levelRulelist = res.data.data;
        }
      }).catch(error=>{
        this.$Message.error("操作失败【" + error + "】");
      })
    },
    routerback: function () {
        this.$router.back(-1)
    },

    getCityListByProvinceId(id, index){
      getCityListByProvinceId(id).then(res=>{
        if (res.data.code == 200) {
          this.itemcityList.splice(index, 1, res.data.data);
        }
      }).catch(error=>{
        this.$Message.error("操作失败【" + error + "】");
      })
    },

    getDistrictListByCityId(id, index){
      getDistrictListByCityId(id).then(res=>{
        if (res.data.code == 200) {
          this.itemdistrictList.splice(index, 1, res.data.data);
        }
      }).catch(error=>{
        this.$Message.error("操作失败【" + error + "】");
      })
    }
  },

  mounted () {
    this.fetchlevelRuleList();
    this.getDetailByid();
    this.fetchprovincelist();

  },
  computed: {
    ...mapState(["provincelist", "citylist", "districtlist"])
  }
};
</script>
<style lang="scss" scoped>
@import "../../styles/common.scss";
.addcustomer_container {
  // @include container_global;
  background-color: white;
  @include margin_global;
  .nav {
      font-size: 20px;
      line-height: 5px;
      float: left;
      padding: 10px 0px 0px 10px;
      position: relative;
    }
  .basic_attribute{
    margin-top: 4vh;
    .basic_tilte{
      @include customer_title_global;
    }
    .consignee_info_title{
      @include customer_title_global;
    }
  }
}
</style>
